<template>
    <header class="home-container" @mouseleave="isEnter=false" :class="{ show: y > 88 }">
      <div class="header">
  
        <div class="header-l">
          <div class="logo">
            <img src="@/assets/logo.png" alt="logo-image">
          </div>
          <ul class="top-list">
            <li 
              v-for="(item) in topBar" 
              :key="item.id"
              @click="toggleTopBar(item)"
              :class="item.id === currentId?'active':''"
            >
              {{ item.title }}
            </li>
          </ul>
        </div>
        <div class="header-r">
          <div class="search">
            <!-- <el-input 
              v-model="keyword" 
              placeholder="搜索想要的书籍名称" 
              clearable 
              @change="selBook"
            />
            <el-icon :size="20" color="#999" style="cursor: pointer;"><Search /></el-icon> -->
            <el-input
              v-model="keyword"
              placeholder="搜索想要的书籍名称"
              clearable
              @input="searchBook"
            >
              <template #append>
                <el-button :icon="Search"/>
              </template>
            </el-input>
  
            <!-- 查找结果列表 -->
            <ul class="searchResList" v-if="resList.length > 0">
              <li 
                v-for="item in resList"
                :key="item.book_id"
                @click="searchBookToDetail(item)"
              >
                <span v-html="eachColor(item.book_name)"></span>
                <hr />
              </li>
            </ul>
  
          </div>
          <div class="shop">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="go to cart"
                placement="bottom"
              >
              <el-badge :value="store.state.cart.countTip" :max="99" class="item">
                <el-icon :size="25" @click="goCart" class="cart-icon"><ShoppingCartFull /></el-icon>
              </el-badge>
            </el-tooltip>
          </div>
          <!-- 未登录 -->
          <div class="login" v-if="!isLogin">
            <router-link to="/login">登录/注册</router-link>
          </div>
          <!-- 已登录 -->
          <div class="userInfo-container" v-else>
            <el-avatar :size="60" :src="userInfo.avatar || defaultSrc" @mouseenter="isEnter=true" style="cursor: pointer;"/>
            <div class="op-info" v-show="isEnter">
              <div class="info-header">
                <el-avatar :size="40" :src="userInfo.avatar || defaultSrc" class="user-avatar" />
                <div class="user-name">
                  <span class="auth">
                    <el-icon><UserFilled /></el-icon>
                    {{ userInfo.manager == 1?'管理员':'用户' }}
                  </span>
                  <span class="name">{{ userInfo.username }}</span>
                </div>
              </div>
              <div class="info-body">
                <div 
                  v-for="item in infoList"
                  :key="item.id"
                  @click="handlerClick(item)"
                >
                          <router-link :to="item.path">
                            <div class="info-item" >
                              <img :src="item.src" />
                              <p>{{ item.text }}</p>
                            </div>
                          </router-link>
                        </div>
                <div class="logout" @click="outLogin">退出登录</div>
              </div>
            </div>
          </div>
  
        </div>
        
      </div>
    </header>
  </template>
  
  <script setup>
  // element
  import { Search, ShoppingCartFull, UserFilled} from '@element-plus/icons-vue'
  import { nextTick, onBeforeMount, reactive, toRefs, watchEffect } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  // api
  import userModelApi from '@/request/api/user.js'

  // vueUse
  import { useScroll } from '@vueuse/core'
  const { y } = useScroll(window);
  
  // router
  const router = useRouter();
  
  // vuex
  import { useStore } from 'vuex';
  
  const store = useStore();
  
  // 默认图片路径
  const defaultSrc = 'src/assets/default-avatar.jpg';
  
  // 导航栏
  let topBar = ref([
    {
      id:1,
      title:'首 页',
      name:'Home',
      path: '/',
      auth: 0
    },
    {
      id:2,
      title:'分 类',
      name:'Category',
      path: '/category',
      auth: 0
    },
    {
      id:3,
      title:'管 理',
      name:'Manage',
      path: '/manage',
      auth: 1
    }
  ])
  
  // 当前导航id
  let currentId = ref(1);
  
  // 监听导航栏事件
  watch(()=>router.currentRoute.value.name,(to) => {
    if(to == 'Home'){
      currentId.value = 1;
    }else if(to == 'Category'){
      currentId.value = 2;
    }else if(to == 'Manage'){
      currentId.value = 3;
    }
    // const loadingInstance = ElLoading.service({ fullscreen: true });
    // setTimeout(() => {
    //   loadingInstance.close()
    // },200)
  },{
    immediate:true
  })
  
  // 点击导航栏跳转
  const toggleTopBar = (item) => {
    if(store.state.user.userInfo.manager != 1 && item.auth == 1){
      // 如果并不是管理员 但是点击了需要管理员权限的列表
    }else{
      currentId.value = item.id;
    }
    router.push({
      path: item.path
    })
  }
  
  // 是否登录
  let isLogin = ref(false);
  
  // 用户信息
  let userInfo = reactive({});
  
  
  // 所有书籍列表
  // item : {
  //   book_id: '100001',
  //   book_name: '深入浅出Node.js'
  // }
  const bookListBySearch = ref([]);
  
  watchEffect(() => {
    bookListBySearch.value = store.getters.getBooksNameAndId;
    // 获取当前购物车列表并存入vuex
    store.dispatch('getCartList', store.state.user.userInfo.username);
  })
  
  // 搜索查询关键字
  let keyword = ref('');
  // 实际查找出来的list
  let resList = ref([]);
  
  // change事件
  const searchBook = () => {
    if(!keyword.value){
      resList.value = [];
      return;
    }
    resList.value = bookListBySearch.value.filter(item => {
      if(item.book_name.includes(keyword.value)){
        return item;
      }
    })
  
  }
  
  // 点击搜索出的结果去详情页
  const searchBookToDetail = ( item ) => {
    router.push({
      path: `/details`,
      // 显式传参
      query: { 
        book_id: item.book_id
      }
    })
  }
  
  // 关键字高亮
  const eachColor = ( content ) => {
    let nt = '<span style="color:#1694FC">' + keyword.value + "</span>";
      return content.replace(keyword.value, nt) + "&nbsp;";
  }
  
  watchEffect(() => {
    // 取出token
    const token = store.state.user.token;
    if(token){
      // 如果有 登录成功
      isLogin.value = true;
    }
    // 赋值 同步不能立即获取 要么action 要么watch
    userInfo = store.state.user.userInfo;
    
  })
  
  
  // 头像那块是否显示操作卡片
  let isEnter = ref(false)
  
  // 头像可操作区域
  const infoList = ref([
    {
      id: 1,
      src: 'src/assets/order.png',
      text: '订单中心',
      path: '/order'
    },
    {
      id: 2,
      src: 'src/assets/setting.png',
      text: '个人中心',
      path: '/my-info'
    },
    {
      id: 3,
      src: 'src/assets/mess.png',
      text: '我的消息',
      path: router.currentRoute.value.fullPath
    },
    {
      id: 4,
      src: 'src/assets/mess.png',
      text: '我的消息',
      path: router.currentRoute.value.fullPath
    }
  ])
  
  // 点击头像可操作区域
  const handlerClick = ( item ) => {
    console.log(item)
  }
  
  // 去购物车页面
  const goCart = () => {
    router.push('/cart')
  }
  
  // 退出登录
  const outLogin = () => {
    ElMessageBox.confirm(
      '确定退出登录吗?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        // 清除本地存储
        store.commit("clearUser");
        isLogin.value = false;
        ElMessage({
          type: 'success',
          message: '退出登录成功',
        })
        router.push('/')
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })
  }
  
  </script>
  
  <style lang='less' scoped>
  header.home-container{
    position: relative;
    width: 100%;
    height: 80px;
    z-index: 999;
    position: fixed;
    top:0;
    left:0;
    box-shadow: 0px 2px 4px rgba(0,0,0,0.16);
    transform: translateY(-100%);
    transition: 0.25s;
    background: rgba(248, 250, 252, 0.75);
    &.show{
        transform: translateY(0);
    }
  }
  .header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 1000px;
    height: 80px;
    margin: 0 auto;
    // border: 1px solid red;
    .header-l{
      display: flex;
      justify-content: space-between;
      align-items: center;
      // border: 1px solid green;
      .logo{
        width: 127px;
        margin-top: 10px;
        img{
          width: 100%;
          height: 100%;
        }
      }
      .top-list{
        display: flex;
        justify-content: space-between;
        height: 50px;
        li{
          line-height: 50px;
          cursor: pointer;
          color:#808080;
          margin-left: 79px;
          font-size:16px;
          &.active{
            position: relative;
            color:#3585FF;
            font-weight: 500;
          }
          &.active::after{
            content: '';
            position: absolute;
            bottom: 0;
            left:0;
            width: 120%;
            height: 2px;
            background: #3585FF;
            margin-left: -10%;
          }
        }
      }
    }
  
    .header-r{
      width: 50%;
      display: flex;
      align-items:center;
      justify-content: space-around;
      .userInfo-container{
        margin-left: 20px;
        position: relative;
        // border:1px solid red;
        .op-info{
          width: 200px;
          height: 194px;
          background-color: #fff;
          border: 1px solid rgba(248, 250, 252, 1);
          box-shadow: 0px 5px 15px 3px #888888;
          position: absolute;
          top: 75px;
          left: 50%;
          transform: translate(-20%);
          z-index: 999;
          display: block;
          border-radius: 10px;
          // border:1px solid red;
          .info-header{
            display: flex;
            // border: 1px solid green;
            align-items: center;
            height: 60px;
            .user-avatar{
              margin:0 10px;
            }
            .user-name{
              margin-top: 10px;
              display: flex;
              flex-direction: column;
              .auth{
                font-size: 12px;
                display: flex;
                align-items: center;
                justify-content: space-around;
              }
            }
          }
          .info-body{
            height: 80px;
            // border: 1px solid green;
            display: flex;
            width: 200px;
            margin-top: 10px;
            flex-wrap: wrap;
            justify-content: space-around;
            position: relative;
            .info-item {
              width: 90px;
              height: 30px;
              display: flex;
              justify-content: space-around;
              align-items: center;
              font-size: 12px;
              font-family: Microsoft YaHei;
              font-weight: 400;
              color: #333333;
              border-radius: 3px;
              cursor: pointer;
              background-color: rgba(0, 0, 0, 0.1) !important;
              img {
                width: 14px;
                height: 16px;
              }
            }
            .logout{
              position: absolute;
              right:5px;
              bottom:-40px;
              font-size: 14px;
              color: rgba(0,0,0,0.8);
              cursor: pointer;
            }
          }
        }
  
        
      }
      .search{
        display: flex;
        align-items:center;
        padding: 0 10px;
        width: 270px;
        height: 43px;
        position: relative;
        border-radius: 5px;
        margin-left: 15px;
        .el-input{
          width: 270px;
          height: 43px;
          border: none;
          background: transparent;
          outline: none;
        }
        .searchResList{
          position: absolute;
          padding: 10px;
          left: 50%;
          transform: translateX(-50%);
          top: 100%;
          background: #fff;
          border: 1px solid gray;
          border-radius: 2px;
          width: 90%;
          height: 200px;
          overflow: hidden;
          overflow-y: scroll;
          li{
            padding: 10px;
            cursor: pointer;
            &:hover{
              background: #efefef;
            }
            span{
              font-size: 15px;
            }
          }
        }
      }
      .shop{
        display: flex;
        align-items: center;
        margin-left: 42px;
        cursor: pointer;
      }
      .login{
        margin-left: 39px;
        font-size: 16px;
        color:#808080;
        cursor: pointer;
      }
    }
    
  }
  
  </style>